import 'package:flutter/material.dart';

import '../utils/api.dart';

class CommentInputSheet extends StatefulWidget {
  final int? parentId;
  final int postId;

  const CommentInputSheet({super.key, this.parentId, required this.postId});

  @override
  State<CommentInputSheet> createState() => _CommentInputSheetState();
}

class _CommentInputSheetState extends State<CommentInputSheet> {
  final TextEditingController _controller = TextEditingController();
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      setState(() {
        // 实时刷新按钮状态
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  bool get _canSend => _controller.text.trim().isNotEmpty && !_isSubmitting;

  Future<void> _submitComment() async {
    final content = _controller.text.trim();
    if (!_canSend) return;

    setState(() => _isSubmitting = true);

    try {
      final res = await Api.post(
        '/comments/add',
        body: {
          'postId': widget.postId,
          'content': content,
          'userId': '8',
          if (widget.parentId != null) 'parentId': widget.parentId,
        },
      );

      if (!mounted) return;

      if (res['code'] == 0) {
        Navigator.pop(context, true);
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text(res['msg'] ?? '评论失败')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('网络异常: $e')));
      }
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: MediaQuery.of(context).viewInsets, // 软键盘遮挡适配
      child: Container(
        padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部小横条
            Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(bottom: 12),
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),

            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // 输入框
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: TextField(
                      controller: _controller,
                      autofocus: true,
                      minLines: 1,
                      maxLines: 5,
                      decoration: InputDecoration(
                        hintText: widget.parentId == null
                            ? '写评论...'
                            : '回复评论...',
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                ),

                const SizedBox(width: 10),

                // 发送按钮
                GestureDetector(
                  onTap: _canSend ? _submitComment : null,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 10,
                    ), // 横向多点，纵向适当
                    decoration: BoxDecoration(
                      color: _canSend ? Colors.black87 : Colors.grey[300],
                      borderRadius: BorderRadius.circular(18), // 圆角矩形，半径12
                    ),
                    child: _isSubmitting
                        ? const SizedBox(
                            width: 16,
                            height: 18,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: Colors.white54,
                            ),
                          )
                        : const Icon(Icons.send, size: 20, color: Colors.white),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
